"use client"

import {TodoList} from "@/components/todo-list"
import {Badge} from "@/components/ui/badge"
import {Button} from "@/components/ui/button"
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
import {Label} from "@/components/ui/label"
import {ScrollArea} from "@/components/ui/scroll-area"
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
import {Textarea} from "@/components/ui/textarea"
import {useToast} from "@/hooks/use-toast"
import {AiService} from "@/lib/ai-service"
import {useAppStore, useOpenaiConfig} from "@/lib/store"
import FileSaver from "file-saver"
import JSZip from "jszip"
import {Code, FileDown, List, Loader2, Send, Sparkles} from "lucide-react"
import pLimit from 'p-limit'
import {useCallback, useRef, useState} from "react"

interface AiAssistantPanelProps {
    onCodeGenerated: (code: string) => void
}

export function AiAssistantPanel({onCodeGenerated}: AiAssistantPanelProps) {
    const { toast } = useToast()
    const openaiConfig = useOpenaiConfig();
    const [prompt, setPrompt] = useState("")
    const [conversation, setConversation] = useState<{ role: "user" | "assistant"; content: string }[]>([])
    const [activeSection, setActiveSection] = useState<"chat" | "todo" | "structure">("chat")
    const conversationRef = useRef<HTMLDivElement>(null)

    // 从全局状态获取数据
    const {
        todoList,
        selectedModel,
        projectStructure,
        isLoading,
        setIsLoading,
        setTodoList,
        setSelectedModel,
        setProjectStructure,
        updateTodoItem,
        getSelectedTodos,
        concurrentLimit,
    } = useAppStore()

    // 获取可用的AI模型
    const availableModels = AiService.getAvailableModels()

    // 示例提示词
    const examplePrompts = [
        "生成一个电商网站的产品展示页面，包含产品列表、筛选和排序功能",
        "创建一个响应式的管理后台仪表盘，包含数据统计图表和最近活动列表",
        "设计一个用户个人资料页面，支持编辑个人信息和上传头像",
        "制作一个带有暗色模式切换的博客文章阅读页面",
    ]

    const handleSubmit = useCallback(async () => {
        if (!prompt.trim() || isLoading) return

        const userMessage = {role: "user" as const, content: prompt}
        const updatedConversation = [...conversation, userMessage]
        setConversation(updatedConversation)
        setPrompt("")
        setIsLoading(true)

        try {
            // 生成TodoList
            const todoItems = await AiService.generateTodoList(prompt, selectedModel, openaiConfig)
            setTodoList(todoItems)

            // 生成项目结构
            const structure = await AiService.generateProjectStructure(todoItems, selectedModel, openaiConfig)
            setProjectStructure(structure)

            const assistantMessage = {
                role: "assistant" as const,
                content: `我已经根据您的需求生成了一个任务列表，包含 ${todoItems.length} 个任务项。您可以在"任务列表"选项卡中查看详情，并选择要生成代码的任务。我还为您生成了一个建议的项目结构，可在"项目结构"选项卡中查看。`,
            }

            const finalConversation = [...updatedConversation, assistantMessage]
            setConversation(finalConversation)
            setActiveSection("todo")

            // Scroll to bottom after message is added
            setTimeout(() => {
                conversationRef.current?.scrollIntoView({behavior: "smooth", block: "end"})
            }, 100)

            toast({
                title: "任务列表生成成功",
                description: `已生成 ${todoItems.length} 个任务项`,
            })
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : "生成失败，请稍后重试"

            toast({
                title: "生成失败",
                description: errorMessage,
                variant: "destructive",
            })

            setConversation([
                ...updatedConversation,
                {role: "assistant", content: `抱歉，生成任务列表时出现了问题：${errorMessage}`},
            ])
        } finally {
            setIsLoading(false)
        }
    }, [conversation, prompt, selectedModel, isLoading, setIsLoading, setTodoList, setProjectStructure, toast])


    const handleGenerateCode = useCallback(async () => {
        setIsLoading(true)
        const selectedTodos = getSelectedTodos()

        if (selectedTodos.length === 0) {
            toast({
                title: "未选择任务",
                description: "请先选择至少一个任务项",
                variant: "destructive",
            })
            return
        }

        try {
            const limit = pLimit(concurrentLimit || 20) // 动态设置最大并发数，默认值为20

            // 创建一个任务队列
            const tasks = selectedTodos.map((todo) =>
                limit(async () => {
                    const prompt = `任务：${todo.title}\n描述：${todo.description}\n\n请生成一个符合这个任务需求的Vue3组件。`

                    // 更新状态为进行中
                    updateTodoItem(todo.id, {status: "in-progress"})

                    // 生成代码
                    const code = await AiService.generateComponent(prompt, selectedModel, openaiConfig)

                    // 更新任务状态和生成的代码
                    updateTodoItem(todo.id, {
                        status: "done",
                        generatedCode: code,
                    })

                    // 如果是第一个任务，将代码传递给预览面板
                    if (todo.id === selectedTodos[0].id) {
                        onCodeGenerated(code)
                    }
                })
            )

            // 并发执行所有任务
            await Promise.all(tasks)

            toast({
                title: "代码生成成功",
                description: `已为 ${selectedTodos.length} 个任务生成代码`,
            })

            // 添加对话消息
            setConversation([
                ...conversation,
                {
                    role: "assistant",
                    content: `我已经为您选择的 ${selectedTodos.length} 个任务生成了代码。您可以在任务列表中查看每个任务的代码，或者下载完整项目。`,
                },
            ])
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : "代码生成失败，请稍后重试"

            toast({
                title: "代码生成失败",
                description: errorMessage,
                variant: "destructive",
            })

            setConversation([...conversation, {
                role: "assistant",
                content: `抱歉，生成代码时出现了问题：${errorMessage}`
            }])
        } finally {
            setIsLoading(false)
        }
    }, [getSelectedTodos, updateTodoItem, selectedModel, onCodeGenerated, conversation, toast, setIsLoading])

    const handleDownloadProject = useCallback(async () => {
        const completedTodos = todoList.filter((todo) => todo.generatedCode)

        if (completedTodos.length === 0) {
            toast({
                title: "没有可下载的代码",
                description: "请先生成至少一个组件的代码",
                variant: "destructive",
            })
            return
        }

        try {
            const zip = new JSZip()

            // 创建基本项目结构
            zip.file(
                "README.md",
                `# Vue3 项目\n\n自动生成的Vue3 + TypeScript + Vite + TailwindCSS项目\n\n## 安装依赖\n\n\`\`\`bash\nnpm install\n\`\`\`\n\n## 开发\n\n\`\`\`bash\nnpm run dev\n\`\`\`\n\n## 构建\n\n\`\`\`bash\nnpm run build\n\`\`\``,
            )
            zip.file(
                "package.json",
                JSON.stringify(
                    {
                        name: "vue-generated-project",
                        private: true,
                        version: "0.0.1",
                        type: "module",
                        scripts: {
                            dev: "vite",
                            build: "vue-tsc && vite build",
                            preview: "vite preview",
                        },
                        dependencies: {
                            vue: "^3.3.4",
                            "vue-router": "^4.2.4",
                            pinia: "^2.1.6",
                        },
                        devDependencies: {
                            "@vitejs/plugin-vue": "^4.2.3",
                            typescript: "^5.1.6",
                            vite: "^4.4.9",
                            "vue-tsc": "^1.8.8",
                            tailwindcss: "^3.3.3",
                            postcss: "^8.4.27",
                            autoprefixer: "^10.4.14",
                        },
                    },
                    null,
                    2,
                ),
            )

            zip.file(
                "tsconfig.json",
                JSON.stringify(
                    {
                        compilerOptions: {
                            target: "ES2020",
                            useDefineForClassFields: true,
                            module: "ESNext",
                            lib: ["ES2020", "DOM", "DOM.Iterable"],
                            skipLibCheck: true,
                            moduleResolution: "bundler",
                            allowImportingTsExtensions: true,
                            resolveJsonModule: true,
                            isolatedModules: true,
                            noEmit: true,
                            jsx: "preserve",
                            strict: true,
                            noUnusedLocals: true,
                            noUnusedParameters: true,
                            noFallthroughCasesInSwitch: true,
                            paths: {
                                "@/*": ["./src/*"],
                            },
                        },
                        include: ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
                        references: [{path: "./tsconfig.node.json"}],
                    },
                    null,
                    2,
                ),
            )

            zip.file(
                "tsconfig.node.json",
                JSON.stringify(
                    {
                        compilerOptions: {
                            composite: true,
                            skipLibCheck: true,
                            module: "ESNext",
                            moduleResolution: "bundler",
                            allowSyntheticDefaultImports: true,
                        },
                        include: ["vite.config.ts"],
                    },
                    null,
                    2,
                ),
            )

            zip.file(
                "vite.config.ts",
                `import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
})
`,
            )

            zip.file(
                "tailwind.config.js",
                `/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
`,
            )

            zip.file(
                "postcss.config.js",
                `export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}
`,
            )

            zip.file(
                "index.html",
                `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Generated Project</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
`,
            )

            // 创建src目录
            const src = zip.folder("src")

            // 添加基本文件
            src?.file(
                "main.ts",
                `import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import './assets/main.css'
import { routes } from './router'

const app = createApp(App)
const pinia = createPinia()
const router = createRouter({
  history: createWebHistory(),
  routes
})

app.use(pinia)
app.use(router)
app.mount('#app')
`,
            )

            src?.file(
                "App.vue",
                `<template>
  <div class="min-h-screen bg-gray-50">
    <header class="bg-white shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex">
            <div class="flex-shrink-0 flex items-center">
              <h1 class="text-xl font-bold text-gray-900">Vue Generated Project</h1>
            </div>
            <nav class="ml-6 flex space-x-8">
              <router-link to="/" class="inline-flex items-center px-1 pt-1 border-b-2 border-indigo-500 text-sm font-medium text-gray-900">
                Home
              </router-link>
              <router-link to="/about" class="inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300">
                About
              </router-link>
            </nav>
          </div>
        </div>
      </div>
    </header>
    
    <main>
      <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <router-view />
      </div>
    </main>
  </div>
</template>
`,
            )

            // 创建assets目录
            const assets = src?.folder("assets")
            assets?.file(
                "main.css",
                `@tailwind base;
@tailwind components;
@tailwind utilities;
`,
            )

            // 创建router目录
            const router = src?.folder("router")
            router?.file(
                "index.ts",
                `import { RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'

export const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  }
]
`,
            )

            // 创建views目录
            const views = src?.folder("views")
            views?.file(
                "Home.vue",
                `<template>
  <div class="py-6">
    <h1 class="text-2xl font-bold text-gray-900 mb-6">Generated Components</h1>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- 这里将放置生成的组件 -->
    </div>
  </div>
</template>
`,
            )

            views?.file(
                "About.vue",
                `<template>
  <div class="py-6">
    <h1 class="text-2xl font-bold text-gray-900 mb-4">About This Project</h1>
    <p class="text-gray-600">
      This project was automatically generated using an AI-powered Vue3 component generator.
      It includes TypeScript, Vite, Vue Router, Pinia, and TailwindCSS.
    </p>
  </div>
</template>
`,
            )

            // 创建components目录
            const components = src?.folder("components")

            // 添加生成的组件
            completedTodos.forEach((todo) => {
                if (todo.generatedCode) {
                    const componentName = todo.title
                        .replace(/[^a-zA-Z0-9]/g, " ")
                        .split(" ")
                        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                        .join("")

                    components?.file(`${componentName}.vue`, todo.generatedCode)
                }
            })

            // 生成并下载zip文件
            const content = await zip.generateAsync({type: "blob"})
            FileSaver.saveAs(content, "vue-generated-project.zip")

            toast({
                title: "项目下载成功",
                description: "已生成完整项目代码包",
            })
        } catch (error) {
            console.error("Error generating zip:", error)
            toast({
                title: "下载失败",
                description: "生成项目包时出错，请重试",
                variant: "destructive",
            })
        }
    }, [todoList, toast])

    const useExamplePrompt = useCallback((example: string) => {
        setPrompt(example)
    }, [])

    return (
        <div className="space-y-6">
            <Card>
                <CardHeader>
                    <CardTitle>AI 助手</CardTitle>
                    <CardDescription>使用AI助手生成Vue3 + TypeScript + TailwindCSS项目</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="space-y-2">
                        <Label htmlFor="model-select">选择模型</Label>
                        <Select value={selectedModel} onValueChange={setSelectedModel}>
                            <SelectTrigger id="model-select">
                                <SelectValue placeholder="选择AI模型"/>
                            </SelectTrigger>
                            <SelectContent>
                                {availableModels.map((model) => (
                                    <SelectItem key={model.id} value={model.id}>
                                        <div className="flex items-center">
                                            <span>{model.name}</span>
                                            <span
                                                className="ml-2 text-xs text-muted-foreground">({model.provider})</span>
                                        </div>
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <p className="text-xs text-muted-foreground">
                            {availableModels.find((m) => m.id === selectedModel)?.description}
                        </p>
                    </div>

                    <div className="space-y-2">
                        <Label>示例提示词</Label>
                        <div className="flex flex-wrap gap-2">
                            {examplePrompts.map((example, index) => (
                                <Button
                                    key={index}
                                    variant="outline"
                                    size="sm"
                                    onClick={() => useExamplePrompt(example)}
                                    className="text-xs"
                                >
                                    {example}
                                </Button>
                            ))}
                        </div>
                    </div>

                    <div className="flex space-x-2 border-b">
                        <Button
                            variant={activeSection === "chat" ? "default" : "ghost"}
                            size="sm"
                            onClick={() => setActiveSection("chat")}
                            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary"
                            data-state={activeSection === "chat" ? "active" : "inactive"}
                        >
                            <Sparkles className="h-4 w-4 mr-2"/>
                            对话
                        </Button>
                        <Button
                            variant={activeSection === "todo" ? "default" : "ghost"}
                            size="sm"
                            onClick={() => setActiveSection("todo")}
                            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary"
                            data-state={activeSection === "todo" ? "active" : "inactive"}
                        >
                            <List className="h-4 w-4 mr-2"/>
                            任务列表
                            {todoList.length > 0 && (
                                <Badge variant="secondary" className="ml-2">
                                    {todoList.length}
                                </Badge>
                            )}
                        </Button>
                        <Button
                            variant={activeSection === "structure" ? "default" : "ghost"}
                            size="sm"
                            onClick={() => setActiveSection("structure")}
                            className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary"
                            data-state={activeSection === "structure" ? "active" : "inactive"}
                        >
                            <Code className="h-4 w-4 mr-2"/>
                            项目结构
                        </Button>
                    </div>

                    {activeSection === "chat" && (
                        <div className="border rounded-md">
                            <ScrollArea className="h-[300px] w-full p-4">
                                {conversation.length === 0 ? (
                                    <div
                                        className="flex flex-col items-center justify-center h-full text-center text-muted-foreground space-y-2">
                                        <Sparkles className="h-8 w-8 text-primary/60"/>
                                        <p>向AI助手描述您想要生成的项目</p>
                                        <p className="text-xs">例如："生成一个电商网站的产品展示页面"</p>
                                    </div>
                                ) : (
                                    <div className="space-y-4">
                                        {conversation.map((message, index) => (
                                            <div key={index}
                                                 className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}>
                                                <div
                                                    className={`max-w-[80%] rounded-lg px-4 py-2 ${
                                                        message.role === "user" ? "bg-primary text-primary-foreground" : "bg-muted"
                                                    }`}
                                                >
                                                    <pre
                                                        className="whitespace-pre-wrap text-sm font-sans">{message.content}</pre>
                                                </div>
                                            </div>
                                        ))}
                                        <div ref={conversationRef}/>
                                    </div>
                                )}
                            </ScrollArea>
                            <div className="p-4 border-t">
                                <div className="flex space-x-2">
                                    <Textarea
                                        value={prompt}
                                        onChange={(e) => setPrompt(e.target.value)}
                                        placeholder="描述您想要生成的项目..."
                                        className="flex-1 min-h-[60px]"
                                        onKeyDown={(e) => {
                                            if (e.key === "Enter" && !e.shiftKey) {
                                                e.preventDefault()
                                                handleSubmit()
                                            }
                                        }}
                                    />
                                    <Button onClick={handleSubmit} disabled={isLoading || !prompt.trim()}
                                            className="self-end">
                                        {isLoading ? <Loader2 className="h-4 w-4 animate-spin"/> :
                                            <Send className="h-4 w-4"/>}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}

                    {activeSection === "todo" && (
                        <div className="border rounded-md p-4">
                            {todoList.length === 0 ? (
                                <div
                                    className="flex flex-col items-center justify-center h-[300px] text-center text-muted-foreground space-y-2">
                                    <List className="h-8 w-8 text-primary/60"/>
                                    <p>还没有任务项</p>
                                    <p className="text-xs">请先在对话中描述您的项目需求</p>
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    <div className="flex justify-between items-center">
                                        <h3 className="text-lg font-medium">任务列表</h3>
                                        <div className="flex space-x-2">
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onClick={handleGenerateCode}
                                                disabled={isLoading || getSelectedTodos().length === 0}
                                            >
                                                {isLoading ? (
                                                    <Loader2 className="h-4 w-4 animate-spin mr-2"/>
                                                ) : (
                                                    <Code className="h-4 w-4 mr-2"/>
                                                )}
                                                生成代码
                                            </Button>
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onClick={handleDownloadProject}
                                                disabled={todoList.filter((t) => t.generatedCode).length === 0}
                                            >
                                                <FileDown className="h-4 w-4 mr-2"/>
                                                下载项目
                                            </Button>
                                        </div>
                                    </div>
                                    <TodoList/>
                                </div>
                            )}
                        </div>
                    )}

                    {activeSection === "structure" && (
                        <div className="border rounded-md p-4">
                            {!projectStructure ? (
                                <div
                                    className="flex flex-col items-center justify-center h-[300px] text-center text-muted-foreground space-y-2">
                                    <Code className="h-8 w-8 text-primary/60"/>
                                    <p>还没有项目结构</p>
                                    <p className="text-xs">请先在对话中描述您的项目需求</p>
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    <h3 className="text-lg font-medium">建议的项目结构</h3>
                                    <ScrollArea className="h-[300px] w-full">
                    <pre className="whitespace-pre-wrap text-sm font-mono p-4 bg-muted rounded-md">
                      {projectStructure}
                    </pre>
                                    </ScrollArea>
                                </div>
                            )}
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    )
}
